package eshop.test;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

import eshop.entity.Products;

@WebServlet("/phantrang.do")
public class ParitionPage extends HttpServlet{
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
			
		
		int page = 1;
		//Lấy số page từ jsp
		if(req.getParameter("page")!=null){
			page = Integer.parseInt(req.getParameter("page"));
		}
		
		int noOfPages ;	 // số page
		int recordPerPage = 5;//số bản ghi trên page
		
		int firstRecord = (page*5)-5;

		
		
		Configuration config = new AnnotationConfiguration().configure();
		SessionFactory factory = config.buildSessionFactory();
		Session session = factory.openSession();
		Transaction t = session.beginTransaction();
		
		String hql="SELECT count(Id) FROM Products";
		Query query = session.createQuery(hql);
		long countProduct =(long)query.uniqueResult();// Lấy tổng số lượng sản phẩm
		//System.out.println(count); // Duyệt số lượng bảng theo tên sản phẩm
		
		//Tính tổng số page
		noOfPages = (int)countProduct/recordPerPage;
		
		//Lấy 5 bản ghi trên page
		hql = "FROM Products";
		query = session.createQuery(hql);
		query.setFirstResult(firstRecord);
		query.setMaxResults(recordPerPage);
		List<Products> plist = query.list();

		
		
		
		
		//Gửi dữ liệu qua jsp
		req.setAttribute("currentPage", page);
		req.setAttribute("noOfPages",noOfPages);
		req.setAttribute("list",plist);
		req.getRequestDispatcher("Test.jsp").forward(req, res);

	}
}
